#include "utility.h"
#include "player/playlistentry.h"
#include "../deps/taglib/include/tstring.h"
#include "../deps/taglib/include/tbytevector.h"

#include <QWidget>
#include <QLineEdit>
#include <QTextEdit>

void util::file_append_extension(QString * filePath, QString ext)
{
    if ( !filePath->endsWith(ext) )
        filePath->append(ext);
}

bool util::fileNameLessThan(const PlaylistEntry* e1, const PlaylistEntry* e2)
{
    if ( e1 == NULL || e2 == NULL )
        return false;

    return e1->fullPath() < e2->fullPath();
}

bool util::titleLessThan(const PlaylistEntry* e1, const PlaylistEntry* e2)
{
    if ( e1 == NULL || e2 == NULL )
        return false;

    return e1->caption().toLower() < e2->caption().toLower();
}

bool util::fileNameGreaterThan(const PlaylistEntry* e1, const PlaylistEntry* e2)
{
    if ( e1 == NULL || e2 == NULL )
        return false;

    return e1->fullPath() > e2->fullPath();
}

bool util::titleGreaterThan(const PlaylistEntry* e1, const PlaylistEntry* e2)
{
    if ( e1 == NULL || e2 == NULL )
        return false;

    return e1->caption().toLower() > e2->caption().toLower();
}

int util::randrange(int max)
{
    double d = (double)qrand()/RAND_MAX;
    return d*(max-1);
}

void util::set_whole_widget_readonly(QWidget* target, bool readonly)
{
    if ( !target || !target->children().count() )
        return;
    foreach(QObject* w, target->children())
    {
        util::set_whole_widget_readonly((QWidget*)w, readonly);

        QString types = typeid(*w).name();
        if (types == "class QLineEdit")
            ((QLineEdit*)w)->setReadOnly(readonly);
        else if (types == "class QTextEdit")
            ((QTextEdit*)w)->setReadOnly(readonly);
    }
}

void util::tagstring_to_qstring(const TagLib::String* source, QString ifNull, QString* output)
{
    if ( !source || source->isNull() )
        *output = ifNull;
    else if ( source->isEmpty() )
        *output = "";
    else if ( source->isAscii() || source->isLatin1() )
        *output = QString::fromLocal8Bit(source->toCString(false));
    else
    {
        TagLib::ByteVector vect = source->data(TagLib::String::UTF16);
        if ( vect.size() > 1 )
        {
            const ushort* utf16 = (const ushort*)vect.data();
            // Salto il primo byte perche' e' l'identificativo UTF16 e le QString non lo digeriscono.
            output->setUtf16(utf16+1, source->length()-1);
        }
        else
            *output = ifNull;
    }
}
